package com.admin_system.service.impl;

import com.admin_system.entity.Notice;
import com.admin_system.mapper.NoticeMapper;
import com.admin_system.service.NoticeService;
import com.admin_system.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 公告服务实现类
 * 处理公告相关的业务逻辑
 */
@Service
@Slf4j
public class NoticeServiceImpl implements NoticeService {
    
    @Autowired
    private NoticeMapper noticeMapper;
    
    /**
     * 获取所有公告列表
     * @return 公告列表
     */
    @Override
    public List<Notice> getAllNotices() {
        try {
            return noticeMapper.findAll();
        } catch (Exception e) {
            log.error("获取公告列表失败", e);
            return null;
        }
    }
    
    /**
     * 根据ID获取公告详情
     * @param id 公告ID
     * @return 公告对象
     */
    @Override
    public Notice getNoticeById(Long id) {
        try {
            return noticeMapper.findById(id);
        } catch (Exception e) {
            log.error("获取公告详情失败, id: {}", id, e);
            return null;
        }
    }
    
    /**
     * 添加公告
     * @param notice 公告对象
     * @param username 发布用户名
     * @return 添加结果
     */
    @Override
    public boolean addNotice(Notice notice, String username) {
        try {
            // 使用真实姓名代替用户名
            String realName = UserUtils.getRealNameByUsername(username);
            
            notice.setPublishTime(new Date());
            notice.setPublishUser(realName);
            
            log.info("添加公告, 标题: {}, 发布者: {}", notice.getTitle(), realName);
            return noticeMapper.insert(notice) > 0;
        } catch (Exception e) {
            log.error("添加公告失败", e);
            return false;
        }
    }
    
    /**
     * 更新公告
     * @param notice 公告对象
     * @return 更新结果
     */
    @Override
    public boolean updateNotice(Notice notice) {
        try {
            return noticeMapper.update(notice) > 0;
        } catch (Exception e) {
            log.error("更新公告失败, id: {}", notice.getId(), e);
            return false;
        }
    }
    
    /**
     * 删除公告
     * @param id 公告ID
     * @return 删除结果
     */
    @Override
    public boolean deleteNotice(Long id) {
        try {
            return noticeMapper.delete(id) > 0;
        } catch (Exception e) {
            log.error("删除公告失败, id: {}", id, e);
            return false;
        }
    }
} 